<template>
    <div class="home">
        <el-container>
            <!-- 顶部导航 -->
            <el-header>
                <el-row type="flex" justify="center">
                    <h1>用户信息管理后台系统</h1>
                </el-row>
            </el-header>

            <!-- 主内容 -->
            <el-main>
                <el-card>
                    <el-row>
                        <el-col :span="8">
                            <el-input
                                placeholder="请输入用户名"
                                v-model="queryInfo.query"
                            >
                                <el-button
                                    slot="append"
                                    icon="el-icon-search"
                                ></el-button>
                            </el-input>
                        </el-col>

                        <el-col :span="6" :offset="1">
                            <el-button
                                type="primary"
                                @click="addUserDialogVisible = true"
                                >添加</el-button
                            >
                        </el-col>
                    </el-row>

                    <el-table :data="tableData" border stripe>
                        <el-table-column prop="username" label="姓名">
                        </el-table-column>
                        <el-table-column prop="mobile" label="手机号">
                        </el-table-column>
                        <el-table-column prop="email" label="邮箱地址">
                        </el-table-column>
                        <el-table-column prop="age" label="年龄">
                        </el-table-column>
                        <el-table-column label="性别">
                            <template slot-scope="scope">
                                <el-tag
                                    effect="plain"
                                    type="primary"
                                    size="mini"
                                    v-if="scope.row.sex === '1'"
                                    >男</el-tag
                                >
                                <el-tag
                                    effect="plain"
                                    type="danger"
                                    v-if="scope.row.sex === '2'"
                                    >女</el-tag
                                >
                            </template>
                        </el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button
                                    type="primary"
                                    icon="el-icon-edit"
                                    size="mini"
                                    @click="handleUserEdit(scope.row)"
                                    round
                                    >编辑</el-button
                                >

                                <el-button
                                    type="danger"
                                    @click="handleUserDelete(scope.row)"
                                    size="mini"
                                    icon="el-icon-delete"
                                    round
                                    >删除</el-button
                                >
                            </template>
                        </el-table-column>
                    </el-table>

                    <el-pagination
                        @size-change="getUserList"
                        @current-change="getUserList"
                        :current-page.sync="queryInfo.pagenum"
                        :page-size.sync="queryInfo.pagesize"
                        :page-sizes="[1, 2, 5, 10, 20, 50]"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="total"
                    >
                    </el-pagination>
                </el-card>
            </el-main>
        </el-container>

        <!-- 添加用户弹框 -->
        <el-dialog
            title="添加用户"
            :visible.sync="addUserDialogVisible"
            width="40%"
        >
            <!-- 添加用户表单 -->
            <!-- :model 表单的键值对对象 -->
            <el-form
                :model="addUserForm"
                :rules="addUserFormRules"
                ref="addUserFormRef"
                label-width="100px"
            >
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="addUserForm.username"></el-input>
                </el-form-item>

                <el-form-item label="密码" prop="password">
                    <el-input
                        v-model="addUserForm.password"
                        show-password
                    ></el-input>
                </el-form-item>

                <el-form-item label="手机号" prop="mobile">
                    <el-input v-model="addUserForm.mobile"></el-input>
                </el-form-item>

                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="addUserForm.email"></el-input>
                </el-form-item>

                <el-form-item label="年龄" prop="age">
                    <el-input v-model="addUserForm.age"></el-input>
                </el-form-item>

                <el-form-item label="性别" prop="sex">
                    <el-select
                        v-model="addUserForm.sex"
                        clearable
                        placeholder="请选择性别"
                    >
                        <el-option label="男" value="1"> </el-option>
                        <el-option label="女" value="2"> </el-option>
                    </el-select>
                </el-form-item>
            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button @click="addUserDialogVisible = false"
                    >取 消</el-button
                >
                <el-button type="primary" @click="handleAddUser"
                    >确 定</el-button
                >
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    created() {
        this.getUserList();
    },
    data() {
        // 密码校验器
        const passwordValidator = (rule, value, callback) => {
            if (/\w{6,20}/.test(value)) {
                callback();
            } else {
                callback(new Error("请输入 6 到 20 位字符"));
            }
        };

        // 年龄校验器
        const checkAge = (rule, value, callback) => {
            if (!value) {
                return callback(new Error("年龄不能为空"));
            }

            // is not a number
            if (isNaN(value)) {
                callback(new Error("请输入数字值"));
            } else {
                if (value < 18) {
                    callback(new Error("必须年满18岁"));
                } else {
                    callback();
                }
            }
        };

        // 邮箱校验器
        const emailValidator = (rule, value, callback) => {
            if (!value) {
                return callback(new Error("邮箱不能为空"));
            }

            // lstyr@outlook.com
            if (/^\w+@\w+\.com$/.test(value)) {
                callback();
            } else {
                callback(new Error("邮箱格式不正确"));
            }
        };

        // 手机号校验器
        const mobileValidator = (rule, value, callback) => {
            if (!value) {
                return callback(new Error("邮箱不能为空"));
            }

            // 13811065680
            if (/^1[3579]\d{9}$/.test(value)) {
                callback();
            } else {
                callback(new Error("手机号格式不正确"));
            }
        };

        return {
            tableData: [],
            queryInfo: {
                query: "",
                pagenum: 1,
                pagesize: 3,
            },
            total: 0,
            addUserDialogVisible: false,
            addUserForm: {
                username: "",
                password: "",
                mobile: "",
                email: "",
                age: "",
                sex: "",
            },
            addUserFormRules: {
                username: [
                    {
                        required: true,
                        message: "请输入用户名",
                        trigger: "change",
                    },
                ],
                password: [
                    {
                        required: true,
                        message: "请输入用户名",
                        trigger: "change",
                    },
                    { validator: passwordValidator, trigger: "change" },
                ],
                mobile: [{ validator: mobileValidator, trigger: "change" }],
                email: [
                    // {
                    //     required: true,
                    //     message: "请输入邮箱",
                    //     trigger: "change",
                    // },
                    { validator: emailValidator, trigger: "change" },
                ],
                age: [{ validator: checkAge, trigger: "change" }],
                sex: [],
            },
        };
    },
    methods: {
        async getUserList() {
            const {
                code,
                data: { list, total },
                message,
            } = await this.$http.get("/users", {
                params: this.queryInfo,
            });
            if (code !== 200) {
                this.$notify.error(message);
                return;
            }
            // 成功拿到了响应的数据
            this.tableData = list;
            this.total = total;
        },
        async handleUserDelete(row) {
            let res = await this.$http.delete(`/users/${row.id}`);
            if (res.code !== 204) {
                this.$message.error(res.message);
                return;
            }
            this.$message.success("删除成功");
            this.getUserList();
        },
        handleUserEdit(row) {
            console.log("row", row);
        },
        handleAddUser() {
            this.$refs.addUserFormRef.validate(async (isValidate) => {
                if (!isValidate) {
                    return;
                }
                // 表单校验成功，发送请求保存到后台
                let res = await this.$http.post("/users", this.addUserForm);
                if (res.code !== 201) {
                    this.$notify.error(res.message);
                    return;
                }
                // 添加成功
                this.getUserList();
                // 关闭弹框
                this.addUserDialogVisible = false;
            });
        },
    },
};
</script>

<style lang="less" scoped>
.home {
    height: 100%;

    .el-container,
    .el-main {
        height: 100%;
    }
    .el-table {
        margin-top: 15px;
    }
    .el-form {
        margin-right: 55px;
    }
}
</style>
